<template>
  <div class="rule-management-container">
    <div class="content-wrapper">
      <h2>规则管理</h2>
      <!-- 规则场景查询 -->
      <div class="scenarios-section">
        <el-autocomplete
          v-model="ruleScenariosInfo.scenariosKey"
          :fetch-suggestions="autoCompleteQuerySearch"
          popper-class="my-autocomplete"
          placeholder="请选择规则场景"
          @select="autoCompleteHandleSeletct"
          style="width: 300px"
        >
          <template #suffix>
            <el-icon
              class="el-input__icon"
              @click="actoCompleteHandleIconClick"
            >
              <edit />
            </el-icon>
          </template>
          <template #default="{ item }">
            <div class="value">{{ item.key }} {{ item.value }}</div>
          </template>
        </el-autocomplete>
      </div>

      <!-- 规则查询 -->
      <div class="query-section">
        <span>规则名称：</span>
        <el-input
          v-model="ruleQueryParams.ruleName"
          class="input-field"
          placeholder="请输入"
        />
        <span>启用状态：</span>
        <el-radio-group v-model="ruleQueryParams.isEnable">
          <el-radio :value="0">启用</el-radio>
          <el-radio :value="1">未启用</el-radio>
        </el-radio-group>
        <div class="button-section">
          <el-button
            type="primary"
            :icon="Search"
            @click="searchRuleByQueryParam(ruleQueryParams)"
            >搜索</el-button
          >
          <el-button
            type="success"
            :icon="Plus"
            @click="openRuleInsertWindow"
            :disabled="!ruleScenariosInfo.scenariosKey"
            >新增</el-button
          >
        </div>
      </div>

      <!-- 规则列表 -->
      <div class="table-section">
        <el-table
          :data="paginatedRules"
          class="rule-table"
          :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
          border
        >
          <el-table-column label="ID" width="80" align="center">
            <template #default="scope">
              <el-popover
                effect="light"
                trigger="hover"
                placement="top"
                width="auto"
              >
                <template #default>
                  <div>{{ scope.row.id }}</div>
                </template>
                <template #reference>
                  <el-tag size="small">{{
                    scope.row.id.toString().substring(0, 4)
                  }}</el-tag>
                </template>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="规则名称" width="180" align="center">
            <template #default="scope">
              <span>{{ scope.row.ruleName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="条件明细" width="280" align="center">
            <template #default="scope">
              <div class="condition-list">
                <div
                  v-for="(item, index) in scope.row.conditionDetail"
                  :key="index"
                  class="list-item"
                >
                  <span class="item-content">{{ item }}</span>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="结果明细" width="180" align="center">
            <template #default="scope">
              <div class="result-list">
                <div
                  v-for="(item, index) in scope.row.resultDetail"
                  :key="index"
                  class="list-item"
                >
                  <span class="item-content">{{ item }}</span>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="生效时间" width="160" align="center">
            <template #default="scope">
              <span>{{
                moment(scope.row.startEffecTime).format("YYYY-MM-DD HH:mm:ss")
              }}</span>
            </template>
          </el-table-column>
          <el-table-column label="失效时间" width="160" align="center">
            <template #default="scope">
              <span>{{
                moment(scope.row.endEffecTime).format("YYYY-MM-DD HH:mm:ss")
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="description"
            label="描述"
            width="150"
            align="center"
          >
          </el-table-column>
          <el-table-column label="状态" width="120" align="center">
            <template #default="scope">
              <el-tag
                :type="scope.row.isEnable == 0 ? 'success' : 'info'"
                size="small"
              >
                {{ scope.row.isEnable == 0 ? "启用" : "未启用" }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            fixed="right"
            width="260"
            align="center"
          >
            <template #default="scope">
              <el-button
                type="info"
                size="small"
                :icon="List"
                @click="getRuleInfo(scope.$index, scope.row)"
                >详情</el-button
              >
              <el-button
                type="danger"
                size="small"
                :icon="Delete"
                @click="deleteRule(scope.row.id)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <!-- 添加分页组件 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="ruleCurrentPage"
            v-model:page-size="rulePageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="ruleInfoList.length"
            @size-change="ruleHandleSizeChange"
            @current-change="ruleHandleCurrentChange"
          />
        </div>
      </div>
    </div>

    <!-- 新增规则 -->
    <el-dialog
      v-model="ruleInsertWindowsEnable"
      title="新增规则"
      width="800px"
      :destroy-on-close="true"
    >
      <el-form :model="insertRule" label-width="100px">
        <el-form-item label="规则名称" required>
          <el-input v-model="insertRule.ruleName" />
        </el-form-item>

        <el-form-item label="条件明细" required>
          <div class="condition-tools">
            <el-select
              v-model="selectedField"
              placeholder="请选择字段"
              style="width: 220px; margin-left: 10px"
              clearable
              :disabled="!ruleScenariosInfo.scenariosKey"
            >
              <el-option
                v-for="item in conditionFieldList"
                :key="item.modelFieldName"
                :label="item.modelFieldZhName || item.fieldName"
                :value="item.modelFieldName"
              >
                <div
                  style="
                    display: flex;
                    justify-content: space-between;
                    font-size: 13px;
                  "
                >
                  <span>{{ item.modelFieldZhName || item.fieldName }}</span>
                  <span style="color: #909399; font-size: 12px">{{
                    item.fieldValueType
                  }}</span>
                </div>
              </el-option>
            </el-select>
            <el-button
              size="small"
              type="success"
              :icon="Plus"
              style="margin-left: 10px"
              @click="addSelectedField"
              :disabled="!selectedField"
            >
              添加字段
            </el-button>
          </div>

          <el-empty
            v-if="!ruleScenariosInfo.scenariosKey"
            description="请先选择规则场景"
            :image-size="80"
          ></el-empty>

          <el-table
            v-else-if="selectedConditionField.length > 0"
            :data="selectedConditionField"
            border
            style="width: 100%; margin-top: 15px"
            :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
          >
            <el-table-column label="字段名称" width="180" align="center">
              <template #default="scope">
                <el-tag size="large" effect="plain" class="field-name-tag">
                  {{ getConditionFieldZhName(scope.row) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作符" width="180" align="center">
              <template #default="scope">
                <el-select
                  :model-value="getConditionOperator(scope.row)"
                  @update:model-value="(val: string) => setConditionOperator(scope.row, val)"
                  placeholder="请选择操作符"
                  style="width: 120px"
                >
                  <el-option
                    v-for="op in getAvailableOperators(scope.row)"
                    :key="op.code"
                    :label="op.displayText"
                    :value="op.code"
                  >
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="条件值" align="center">
              <template #default="scope">
                <!-- 基本类型输入框 -->
                <template v-if="getFieldValueType(scope.row) === 'basicType'">
                  <!-- 普通输入框 - 非介于/不介于 -->
                  <template
                    v-if="
                      !['between', 'notBetween'].includes(
                        getConditionOperator(scope.row)
                      )
                    "
                  >
                    <el-input
                      v-if="
                        !['isEmpty', 'isNotEmpty'].includes(
                          getConditionOperator(scope.row)
                        )
                      "
                      :model-value="getConditionValue(scope.row)"
                      @update:model-value="(val: string) => setConditionValue(scope.row, val)"
                      placeholder="请输入条件值"
                      style="width: 200px"
                    ></el-input>
                  </template>

                  <!-- 介于/不介于 双输入框 -->
                  <template v-else>
                    <div style="display: flex; align-items: center; gap: 5px">
                      <el-input
                        :model-value="getConditionValueStart(scope.row)"
                        @update:model-value="(val: string) => setConditionValueStart(scope.row, val)"
                        placeholder="最小值"
                        style="width: 95px"
                      ></el-input>
                      <span>至</span>
                      <el-input
                        :model-value="getConditionValueEnd(scope.row)"
                        @update:model-value="(val: string) => setConditionValueEnd(scope.row, val)"
                        placeholder="最大值"
                        style="width: 95px"
                      ></el-input>
                    </div>
                  </template>
                </template>

                <!-- 枚举类型下拉框 -->
                <template
                  v-else-if="getFieldValueType(scope.row) === 'enumConstant'"
                >
                  <!-- 普通单选下拉 -->
                  <el-select
                    v-if="
                      !['in', 'notIn'].includes(
                        getConditionOperator(scope.row)
                      ) &&
                      !['isEmpty', 'isNotEmpty'].includes(
                        getConditionOperator(scope.row)
                      )
                    "
                    :model-value="getConditionValue(scope.row)"
                    @update:model-value="(val: string) => setConditionValue(scope.row, val)"
                    placeholder="请选择条件值"
                    style="width: 200px"
                    clearable
                  >
                    <el-option
                      v-for="item in getEnumOptions(scope.row)"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>

                  <!-- 多选下拉框 - 属于/不属于 -->
                  <el-select
                    v-else-if="
                      ['in', 'notIn'].includes(getConditionOperator(scope.row))
                    "
                    :model-value="getConditionValueArray(scope.row)"
                    @update:model-value="(val: string[]) => setConditionValueArray(scope.row, val)"
                    multiple
                    collapse-tags
                    placeholder="请选择条件值"
                    style="width: 200px"
                  >
                    <el-option
                      v-for="item in getEnumOptions(scope.row)"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </template>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100" align="center">
              <template #default="scope">
                <el-button
                  type="danger"
                  size="small"
                  :icon="Delete"
                  circle
                  @click="removeConditionField(scope.row)"
                />
              </template>
            </el-table-column>
          </el-table>

          <el-empty
            v-else
            description="暂无条件字段，请先选择并添加字段"
            :image-size="80"
          ></el-empty>
        </el-form-item>

        <el-form-item label="结果明细" required>
          <div class="condition-tools">
            <el-select
              v-model="resultFieldSelected"
              placeholder="请选择字段"
              style="width: 220px; margin-left: 10px"
              clearable
              :disabled="!ruleScenariosInfo.scenariosKey"
            >
              <el-option
                v-for="item in resultFieldList"
                :key="item.modelFieldName"
                :label="item.modelFieldZhName || item.fieldName"
                :value="item.modelFieldName"
              >
                <div
                  style="
                    display: flex;
                    justify-content: space-between;
                    font-size: 13px;
                  "
                >
                  <span>{{ item.modelFieldZhName || item.fieldName }}</span>
                  <span style="color: #909399; font-size: 12px">{{
                    item.fieldValueType
                  }}</span>
                </div>
              </el-option>
            </el-select>
            <el-button
              size="small"
              type="success"
              :icon="Plus"
              style="margin-left: 10px"
              @click="addResultSelectedField"
              :disabled="!resultFieldSelected"
            >
              添加字段
            </el-button>
          </div>

          <el-empty
            v-if="!ruleScenariosInfo.scenariosKey"
            description="请先选择规则场景"
            :image-size="80"
          ></el-empty>

          <el-table
            v-else-if="selectedResultField.length > 0"
            :data="selectedResultField"
            border
            style="width: 100%; margin-top: 15px"
            :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
          >
            <el-table-column label="字段名称" width="180" align="center">
              <template #default="scope">
                <el-tag size="large" effect="plain" class="field-name-tag">
                  {{ getResultFieldZhName(scope.row) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="条件值" align="center">
              <template #default="scope">
                <!-- 基本类型输入框 -->
                <template
                  v-if="getResultFieldValueType(scope.row) === 'basicType'"
                >
                  <el-input
                    :model-value="getResultValue(scope.row)"
                    @update:model-value="(val: string) => setResultValue(scope.row, val)"
                    placeholder="请输入条件值"
                    style="width: 200px"
                  ></el-input>
                </template>

                <!-- 枚举类型下拉框 - 始终为多选 -->
                <template
                  v-else-if="
                    getResultFieldValueType(scope.row) === 'enumConstant'
                  "
                >
                  <el-select
                    :model-value="getResultValueArray(scope.row)"
                    @update:model-value="(val: string[]) => setResultValueArray(scope.row, val)"
                    multiple
                    collapse-tags
                    placeholder="请选择条件值"
                    style="width: 200px"
                  >
                    <el-option
                      v-for="item in getResultEnumOptions(scope.row)"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </template>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100" align="center">
              <template #default="scope">
                <el-button
                  type="danger"
                  size="small"
                  :icon="Delete"
                  circle
                  @click="removeResultField(scope.row)"
                />
              </template>
            </el-table-column>
          </el-table>

          <el-empty
            v-else
            description="暂无条件字段，请先选择并添加字段"
            :image-size="80"
          ></el-empty>
        </el-form-item>

        <el-form-item label="结果行为">
          <el-input v-model="insertRule.resultAction" />
        </el-form-item>

        <el-form-item label="规则描述">
          <el-input
            v-model="insertRule.description"
            type="textarea"
            :rows="3"
          />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="生效时间" required>
              <el-date-picker
                v-model="insertRule.startEffecTime"
                type="datetime"
                placeholder="请设置生效时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="失效时间" required>
              <el-date-picker
                v-model="insertRule.endEffecTime"
                type="datetime"
                placeholder="请设置失效时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="是否启用">
          <el-radio-group v-model="insertRule.isEnable">
            <el-radio :value="0">启用</el-radio>
            <el-radio :value="1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="ruleInsertWindowsEnable = false">取消</el-button>
          <el-button type="primary" @click="insertRuleOnSubmit(insertRule)"
            >新建</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import useRuleManagement from "@/hooks/useRuleManagement";
import { computed, onMounted, ref, watch } from "vue";
import { Search, Edit, Delete, Plus, List } from "@element-plus/icons-vue";
import moment from "moment";

const {
  ruleScenariosInfo,
  ruleScenariosOptionList,
  ruleQueryParams,
  ruleInsertWindowsEnable,
  ruleInfoList,
  ruleCurrentPage,
  rulePageSize,
  conditionFieldList,
  resultFieldList,
  insertRule,
  updateRule,
  selectedConditionField,
  selectedResultField,
  selectedConditionFieldWindowsEnable,
  autoCompleteQuerySearch,
  autoCompleteHandleSeletct,
  actoCompleteHandleIconClick,
  loadRuleScenariosOptionList,
  searchRuleByQueryParam,
  searchConditionFieldItem,
  getRuleInfo,
  deleteRule,
  ruleHandleSizeChange,
  ruleHandleCurrentChange,
  openRuleInsertWindow,
  insertRuleOnSubmit,
  updateRuleOnSubmit,
  handleConditionFieldChange,
  loadConditionFields,
  loadResultFields,
  addConditionField,
  addResultField,
  removeConditionField,
  getConditionOperator,
  getConditionValue,
  setConditionOperator,
  setConditionValue,
  getConditionFieldZhName,
  getResultFieldZhName,
  getResultOperator,
  setResultOperator,
  setResultValue,
  getResultValue,
  removeResultField,
  getOperator,
  getFieldValueType,
  getResultFieldValueType,
  getAvailableOperators,
  getEnumOptions,
  getResultEnumOptions,
  getConditionValueStart,
  getConditionValueEnd,
  setConditionValueStart,
  setConditionValueEnd,
  getConditionValueArray,
  setConditionValueArray,
  getResultValueArray,
  setResultValueArray,
} = useRuleManagement();

const paginatedRules = computed(() => {
  const start = (ruleCurrentPage.value - 1) * rulePageSize.value;
  const end = start + rulePageSize.value;
  return ruleInfoList.slice(start, end);
});

const selectedField = ref("");
const resultFieldSelected = ref("");

function addSelectedField() {
  if (selectedField.value) {
    addConditionField(selectedField.value);
    selectedField.value = "";
  }
}

function addResultSelectedField() {
  if (resultFieldSelected.value) {
    addResultField(resultFieldSelected.value);
    resultFieldSelected.value = "";
  }
}

onMounted(() => {
  // 加载规则场景列表
  loadRuleScenariosOptionList();

  // 监听规则场景变化，自动加载字段列表
  watch(
    () => ruleScenariosInfo.scenariosKey,
    (newVal, oldVal) => {
      if (newVal && newVal !== oldVal) {
        console.log("规则场景变化，自动加载字段列表");
        loadConditionFields();
        loadResultFields();
      }
    }
  );
});
</script>

<style scoped>
.rule-management-container {
  margin: 0 auto;
  padding: 15px;
}

.content-wrapper {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.rule-management-container h2 {
  font-size: 22px;
  color: #303133;
  margin-bottom: 20px;
  border-left: 4px solid #409eff;
  padding-left: 10px;
}

.scenarios-section {
  margin-bottom: 15px;
}

.query-section {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding: 15px;
  background: #f5f7fa;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.input-field {
  width: 200px;
  margin-right: 10px;
}

.button-section {
  margin-left: 15px;
  display: flex;
  gap: 10px;
}

:deep(.el-form-item__content) {
  flex: 1;
  flex-direction: column;
}

.section-title {
  font-size: 16px;
  color: #606266;
  margin-bottom: 15px;
  font-weight: 500;
}

.table-section {
  background: #fff;
  padding: 10px 0;
}

.rule-table {
  width: 100%;
  margin-bottom: 15px;
  border-radius: 4px;
  overflow: hidden;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 弹窗样式 */
:deep(.el-dialog__header) {
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 15px;
}

:deep(.el-dialog__footer) {
  border-top: 1px solid #f0f0f0;
  padding-top: 15px;
}

:deep(.el-dialog__body) {
  padding: 20px 30px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

/* 条件字段相关样式 */
.condition-tools {
  display: flex;
  align-items: center;
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 4px;
  margin-bottom: 10px;
}

.field-name-tag {
  width: 100%;
  text-align: center;
  padding: 6px 0;
}

/* 表格内的标签样式 */
:deep(.el-tag) {
  font-weight: normal;
}

.condition-list {
  margin: 0;
  padding: 0;
}

.result-list {
  margin: 0;
  padding: 0;
}

.list-item {
  text-align: left;
  display: flex;
  align-items: center;
  margin: 4px 0;
}
</style>
